<?php
class Service_Model_RagDic
{
    /**
     * Web scrap a request to www.realacademiagalega.org dictionary
     * 
     * @param string $q
     * @return string
     */
    public function query($q)
    {
        $uri = 'http://www.realacademiagalega.org/rag_dicionario/searchNoun.do';
        $client = new Zend_Http_Client($uri,
            array(
                'maxredirects'  => 0,
                'timeout'       => 30,
                'useragent'     => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)',
                'keepalive'     => false,
                'httpversion'   => '1.1',
            )
        );
        
        // GET parameter
        $client->setParameterGet('nounTitle', $q);
        
        // Method via GET
        $client->setMethod(Zend_Http_Client::GET);        
        
        $response = $client->request();
        $html = $response->getBody();
        
        $matches = array();
        preg_match_all('/<div class="description">(.*?)<\/div>/s', $html, $matches);
        if(!isset($matches[1])) {
            return null;
        }
        
        $html = $matches[1][0];        
        $text = trim( html_entity_decode(strip_tags($html, '<a><div><p><em><i><b><strong>'), ENT_COMPAT, 'UTF-8') );
        
        if($text=='') {
            return null;
        }
        
        return $text;
    }        
}
